﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Web;

namespace tjb.Utility
{
    /// <summary>
    /// 
    /// </summary>
    public class DllInvoke
    {

        [DllImport("kernel32.dll")]
        private extern static IntPtr LoadLibrary(String path);
        [DllImport("kernel32.dll")]
        private extern static IntPtr GetProcAddress(IntPtr lib, String funcName);
        [DllImport("kernel32.dll")]
        private extern static bool FreeLibrary(IntPtr lib);
        private IntPtr hLib;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="DLLPath"></param>
        public DllInvoke(String DLLPath)
        {
            hLib = LoadLibrary(DLLPath);
        }
        /// <summary>
        /// 
        /// </summary>
        ~DllInvoke()
        {
            FreeLibrary(hLib);
        }


        /// <summary>
        /// 将要执行的函数转换为委托
        /// </summary>
        /// <param name="APIName"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public Delegate Invoke(String APIName, Type t)
        {
            IntPtr api = GetProcAddress(hLib, APIName);
            return (Delegate)Marshal.GetDelegateForFunctionPointer(api, t);
        }



    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="command"></param>
    /// <param name="inf"></param>
    /// <returns></returns>
    public delegate int Compile(String command, out StringBuilder inf);//编译
    class mytest
    {
        void test()
        {
            DllInvoke dll = new DllInvoke(HttpContext.Current.Server.MapPath(@"~/Bin/Judge.dll"));
            Compile compile = (Compile)dll.Invoke("Compile", typeof(Compile));
            StringBuilder inf = null;
            compile(@"gcc a.c -o a.exe", out inf); //这里就是调用我的DLL里定义的Compile函数
        }


        public void mytest0(string Name)
        {
            Console.WriteLine(Name + "");
        }
    }
    /****
        public delegate int Compile(String command, StringBuilder inf);//编译
        DllInvoke dll ＝ new DllInvoke(Server.MapPath(@"~/Bin/Judge.dll"));
        Compile compile = (Compile)dll.Invoke("Compile", typeof(Compile));
        StringBuilder inf;
        compile(@“gcc a.c -o a.exe“,inf); //这里就是调用我的DLL里定义的Compile函数
        ****/
}
